package com.example.satoken.handler;

import cn.hutool.json.JSONUtil;
import com.example.satoken.annotion.BaseResponse;
import com.example.satoken.common.ResponseCode;
import com.example.satoken.common.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一响应体处理器
 *
 * @author wpz
 * @date 2023/05/23
 */
@ControllerAdvice(annotations = BaseResponse.class)
@Slf4j
public class ResponseResultHandlerAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        log.info("returnType:{}" + returnType);
        log.info("converterType:{}" + converterType);
        return true;
    }

    /**
     * @param body
     * @param returnType
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 判断响应的Content-Type为JSON格式的body
        if (MediaType.APPLICATION_JSON.equals(selectedContentType) || MediaType.APPLICATION_JSON_UTF8.equals(selectedContentType)) {
            // 如果响应返回的对象为统一响应体，则直接返回body
            if (body instanceof ResponseResult) {
                return body;
            } else {
                // 只有正常返回的结果才会进入这个判断流程，所以返回正常成功的状态码
                ResponseResult responseResult = new ResponseResult(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMsg(), body);
                return responseResult;
            }
        }
        // 已经是ResponseResult类型的直接返回，不然就转成String的字符串的ResponseResult返回。
        if (body instanceof ResponseResult) {
            return body;
        }
        // 非JSON的ResponseResult格式body直接返回即可转为字符串类型即可等等。
        return JSONUtil.toJsonStr(new ResponseResult(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMsg(), (body)));
    }
}
